# default values
setenv load_addr "0x44000000"
setenv verbosity "7"
setenv console "both"
setenv disp_mem_reserves "off"
setenv disp_mode "1920x1080p60"
setenv rootdev "/dev/mmcblk0p2"
setenv rootfstype "ext4"
setenv rootdelay "2"

# Print boot source
itest.b *0x28 == 0x00 && echo "U-boot loaded from SD"
itest.b *0x28 == 0x02 && echo "U-boot loaded from eMMC or secondary SD"
itest.b *0x28 == 0x03 && echo "U-boot loaded from SPI"

echo ""
echo "Boot script loaded from ${devtype}"
echo ""

echo "load uEnv.txt"
if load ${devtype} 0:1 ${load_addr} uEnv.txt || load ${devtype} 0:2 ${load_addr} /boot/uEnv.txt; then
	env import -t ${load_addr} ${filesize}
fi

if test "${console}" = "display" || test "${console}" = "both"; then setenv consoleargs "console=tty1"; fi
if test "${console}" = "serial" || test "${console}" = "both"; then setenv consoleargs "${consoleargs} console=ttyS0,115200"; fi

# get PARTUUID of first partition on SD/eMMC it was loaded from
# mmc 0 is always mapped to device u-boot (2016.09+) was loaded from
if test "${devtype}" = "mmc"; then part uuid mmc 0:1 partuuid; fi

setenv bootargs "root=${rootdev} rootfstype=${rootfstype} rootwait rootdelay=${rootdelay} init=${init} ${consoleargs} cgroup_enable=memory swapaccount=1 hdmi.audio=EDID:0 disp.screen0_output_mode=${disp_mode} panic=10 consoleblank=0 enforcing=0 loglevel=${verbosity} ubootpart=${partuuid} ubootsource=${devtype} ${extraargs} ${extraboardargs}"

if test "${disp_mem_reserves}" = "off"; then setenv bootargs "${bootargs} sunxi_ve_mem_reserve=0 sunxi_g2d_mem_reserve=0 sunxi_fb_mem_reserve=16"; fi

echo "load zImage"
load ${devtype} 0:1 ${kernel_addr_r} zImage || load ${devtype} 0:2 ${kernel_addr_r} /boot/zImage

if load ${devtype} 0:1 ${ramdisk_addr_r} uInitrd || load ${devtype} 0:2 ${ramdisk_addr_r} /boot/uInitrd; then
	echo "have uInitrd"
	echo ""
	if load ${devtype} 0:1 ${fdt_addr_r} ${fdtfile} || load ${devtype} 0:2 ${fdt_addr_r} /boot/${fdtfile} ;then
		echo ""
		echo "boot OrangePi mainline linux"
		echo ""
		bootz ${kernel_addr_r} ${ramdisk_addr_r} ${fdt_addr_r}
	else
		load ${devtype} 0:1 ${fdt_addr_r} script.bin || load ${devtype} 0:2 ${fdt_addr_r} /boot/script.bin
		echo ""
		echo "boot OrangePi sunxi linux"
		echo ""
		bootz ${kernel_addr_r} ${ramdisk_addr_r}
	fi
else
	echo "no uInitrd"
	if load ${devtype} 0:1 ${fdt_addr_r} ${fdtfile} || load ${devtype} 0:2 ${fdt_addr_r} /boot/${fdtfile} ;then
		echo ""
		echo "boot OrangePi mainline linux"
		echo ""
		bootz ${kernel_addr_r} - ${fdt_addr_r}
	else
		load ${devtype} 0:1 ${fdt_addr_r} script.bin || load ${devtype} 0:2 ${fdt_addr_r} /boot/script.bin
		echo ""
		echo "boot OrangePi sunxi linux"
		echo ""
		bootz ${kernel_addr_r}
	fi
fi


# Recompile with:
# mkimage -C none -A arm -T script -d orangepi.cmd boot.scr
# mkimage -A arm -T ramdisk -C none -n uInitrd -d initrd.img uInitrd
